package com.szgz.platform.handler;

import com.szgz.platform.result.ApiResponse;
import com.szgz.platform.exception.BusinessException;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;


/**
 * 全局异常处理
 */
@RestControllerAdvice(basePackages = "com.szgz.platform")
@Slf4j
public class GlobalExceptionHandler {

	@ExceptionHandler(BusinessException.class)
	public ApiResponse<Void> handleBusiness(BusinessException ex) {
		return ApiResponse.fail(ex.getCode(), ex.getMessage());
	}

	@ExceptionHandler({MissingServletRequestParameterException.class})
	public ApiResponse<Void> handleMissingParam(MissingServletRequestParameterException ex) {
		return ApiResponse.fail(400, "缺少必要参数: " + ex.getParameterName());
	}

	@ExceptionHandler({MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class})
	public ApiResponse<Void> handleTypeMismatch(Exception ex) {
		return ApiResponse.fail(400, "参数类型或格式错误");
	}

	@ExceptionHandler(ConstraintViolationException.class)
	public ApiResponse<Void> handleValidation(ConstraintViolationException ex) {
		return ApiResponse.fail(400, ex.getMessage());
	}

	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public ApiResponse<Void> handleMethodNotSupported(HttpRequestMethodNotSupportedException ex) {
		return ApiResponse.fail(405, "请求方法不被支持: " + ex.getMethod());
	}

	@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
	public ApiResponse<Void> handleMediaType(HttpMediaTypeNotSupportedException ex) {
		return ApiResponse.fail(415, "媒体类型不被支持");
	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public ApiResponse<Void> handleNotFound(NoHandlerFoundException ex) {
		return ApiResponse.fail(404, "资源不存在");
	}

	@ExceptionHandler(Exception.class)
	public ApiResponse<Void> handleOther(Exception ex) {

        log.error("服务器内部错误", ex);
		return ApiResponse.fail(500, "服务器内部错误");
	}
}

